package com.qbw.app.module.mine.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;

import com.http.okhttp.HttpTask;
import com.lib.util.AppUtil;
import com.lib.util.ResUtil;
import com.lib.util.SPUtils;
import com.lib.util.ToastUtil;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.qbw.app.Config;
import com.qbw.app.Constant;
import com.qbw.app.R;
import com.qbw.app.databinding.VehicleActivityFirmwareUpgradeBinding;
import com.qbw.app.model.BaseModel;
import com.qbw.app.model.BaseResponse;
import com.qbw.app.model.FirmwareUpgrade;
import com.qbw.app.module.common.activity.CommonActivity;
import com.qbw.app.module.common.activity.WebViewActivity;
import com.qbw.app.module.common.fragment.ExitAppDialogFragment;
import com.qbw.app.module.common.fragment.OkCancelDialogFragment;
import com.qbw.app.request.impl.CommonRequest;
import com.qbw.app.request.impl.UserRequest;
import com.qbw.core.okhttp.JsonCallback;
import com.st.BlueSTSDK.Manager;
import com.st.BlueSTSDK.Node;
import com.st.BlueSTSDK.gui.NodeConnectionService;
import com.st.BlueSTSDK.gui.NodeListActivity;
import com.tbox.tbsdk.TBoxSDK;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.jpush.android.api.JPushInterface;

import static com.qbw.app.request.impl.CommonRequest.VEHICE_FIRMWAREVERSION;
import static com.qbw.app.request.impl.CommonRequest.VEHICE_UPDATEFIRMWAREVERSION;

/**
 * @author QBW
 * @date 2019-10-20
 */
public class FirmwareUpgradeActivity extends CommonActivity<VehicleActivityFirmwareUpgradeBinding> implements ExitAppDialogFragment.Listener{


    private final static String TAG = FirmwareUpgradeActivity.class.getCanonicalName();
    String fileMkdirPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/btota/";
    private TBoxSDK tBoxSDK;
    private Manager mManager;
    private long downloadLength;
    private FirmwareUpgrade firmwareUpgrade;
    private LoadingPopupView loadingPopup;
    public static void start(Context context) {
        Intent intent = new Intent(context, FirmwareUpgradeActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.vehicle_activity_firmware_upgrade;
    }


    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int progress = msg.what;
            if(progress == 100){
                mBinding.tvProgress.setText(getResources().getString(R.string.oat_file_download_complete));
                dissDialog();
            }else{
                mBinding.tvProgress.setText(getResources().getString(R.string.oat_file_downloading)+"  "+progress +" %");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding.title.setListener(this);
        mBinding.title.setTitle(R.string.ota_update);
        mManager = Manager.getSharedInstance();
        mBinding.tvVersion.setText(SPUtils.getInstance().getString(Constant.KEY_BT_VERSION_NAME));
        File fileMkdir = new File(fileMkdirPath);
        if (!fileMkdir.exists()) {
            fileMkdir.mkdir();
        }else{
            File file = new File(fileMkdirPath);
            deleteAllFiles(file);
        }

        mBinding.otaUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(tBoxSDK.getBluetoothGatt() !=null){
                    if(firmwareUpgrade != null){
                        if(firmwareUpgrade.getUpdateState() == 0){
                            showDialog();
                        }else if(firmwareUpgrade.getUpdateState() == 1){
                            ToastUtil.showToast(FirmwareUpgradeActivity.this,"已经是最新的版本");
                        }
                    }else{
                        ToastUtil.showToast(FirmwareUpgradeActivity.this,"请先连接车辆蓝牙");

                    }
                }else{
                    if(SPUtils.getInstance().getBoolean(Constant.KEY_BT_OTA_MODEL)){
                        showDialog();
                    }else{
                        ToastUtil.showToast(FirmwareUpgradeActivity.this,"请先连接车辆蓝牙");

                    }
                }

            }
        });
        tBoxSDK = TBoxSDK.getInstance(this);

//        resetNodeList();
////        startNodeDiscovery();
//
        mGeneralManager.getRequestManager()
                .getCommonRequest()
                .checkFirmwareVersion(SPUtils.getInstance().getString(Constant.KEY_VEHICLECODE),"4",FirmwareUpgradeActivity.this)
                .execute();
    }



    private void checkFirmwareVersionFeedback(){
        JSONObject jb = new JSONObject();
        try {
            jb.put("deviceCode", SPUtils.getInstance().getString(Constant.KEY_VEHICLECODE));
            jb.put("type", 4);
            jb.put("updateState", 1);
            jb.put("versionNo", SPUtils.getInstance().getString(Constant.KEY_BT_VERSIONNO));


        } catch (JSONException e) {
            e.printStackTrace();
        }

        OkGo.<BaseModel>post(Config.getUrl()+"/"+VEHICE_UPDATEFIRMWAREVERSION)
                .tag(this)
                .upJson(jb)
                .execute(new JsonCallback<BaseModel>() {
                    @Override
                    public void onSuccess(Response<BaseModel> response) {
//                        ToastUtil.showToast(FirmwareUpgradeActivity.this,response.body().toString());

                    }

                    @Override
                    public void onError(Response<BaseModel> response) {
                        super.onError(response);

                    }
                });
    }

    private void showDialog(){
        new XPopup.Builder(this)

                .asConfirm("温馨提示", " 当前操作进入蓝牙固件升级模式\n" +
                        "您确定要升级吗？",
                new OnConfirmListener() {
                    @Override
                    public void onConfirm() {
                        tBoxSDK.swtichOta();
                        startActivity(new Intent(FirmwareUpgradeActivity.this,FwUpgradeActivity.class));
                    }
                })

                .show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(SPUtils.getInstance().getBoolean(Constant.KEY_BT_FIRMWARE_UPGRADE_SUCCESSFUL,false)){
            checkFirmwareVersionFeedback();
            SPUtils.getInstance().put(com.tbox.tbsdk.Constant.KEY_BT_OTA_MODEL,false);
            SPUtils.getInstance().put(Constant.KEY_BT_FIRMWARE_UPGRADE_SUCCESSFUL,false);

            exitApp();
        }

    }


    private void exitApp(){
        ExitAppDialogFragment.createInstance(0, ResUtil.getString(R.string.exit_app))
                .show(getSupportFragmentManager(), "logout");
    }


    @Override
    public void onHttpSuccess(HttpTask httpTask, Object entity) {
        super.onHttpSuccess(httpTask, entity);
        String method = httpTask.getMethod();
        if (method.equals(VEHICE_FIRMWAREVERSION)) {
            FirmwareUpgrade.Response response = (FirmwareUpgrade.Response) entity;
            firmwareUpgrade = response.getData();
            if(response.getData()!= null){
                SPUtils.getInstance().put(Constant.KEY_BT_VERSIONNO,response.getData().getVersionNo());
                SPUtils.getInstance().put(Constant.KEY_BT_VERSION_NAME,response.getData().getVersionNo());
                mBinding.tvVersion.setText(response.getData().getVersionName());
                if(response.getData().getUpdateState() == 1){
                    mBinding.tvProgress.setText("已经是最新的版本");
                }else {
                    loadingDialog();
                    downFile(response.getData().getVersionUrl());
                }
            }

        }
    }

    @Override
    public void onHttpFailed(HttpTask httpTask, int errorCode, String message) {
        super.onHttpFailed(httpTask, errorCode, message);
        String method = httpTask.getMethod();
        if (method.equals(VEHICE_FIRMWAREVERSION)) {
            mBinding.tvVersion.setText(SPUtils.getInstance().getString(Constant.KEY_BT_VERSION_NAME));

        }
    }



    private void downFile(String versionUrl) {
        new Thread(new Runnable() {
            @Override
            public void run() {
//                ((BaseFActivity) _mActivity).showProgress("正在获取经书内容...");

                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL(versionUrl);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    long size = connection.getContentLength();//文件大小
                    String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/btota/btota.bin";

                    File file = new File(filePath);
                    if(file.isFile()){
                        file.createNewFile();
                    }


                    //此时获取的是字节流
                    InputStream is = connection.getInputStream();
                    FileOutputStream fileOutputStream = null;
                    fileOutputStream = new FileOutputStream(file, true);
                    byte[] buffer = new byte[2048];//缓冲数组2kB
                    int len;
                    while ((len = is.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, len);
                        downloadLength += len;
                        updateProgress(size);

                    }
                    fileOutputStream.flush();
                    is.close();

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
//                    if (reader != null) {
//                        try {
//                            reader.close();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }


    private void updateProgress(long size){
        int progress = (int)(downloadLength*100/size);
        Message message = new Message();
        message.what = progress;
        handler.sendMessage(message);


    }


    private Manager.ManagerListener mUpdateDiscoverGui = new Manager.ManagerListener() {

        /**
         * call the stopNodeDiscovery for update the gui state
         * @param m manager that start/stop the process
         * @param enabled true if a new discovery start, false otherwise
         */
        @Override
        public void onDiscoveryChange(@NonNull Manager m, boolean enabled) {
            Log.d(TAG, "onDiscoveryChange " + enabled);
            if (!enabled)
                //run
                runOnUiThread(() -> stopNodeDiscovery());
        }//onDiscoveryChange

        /**
         * Hide the SwipeRefreshLayout refresh after that we discover the first node
         * @param m manager that discover the node
         * @param node new node discovered
         */
        @Override
        public void onNodeDiscovered(@NonNull Manager m, Node node) {
            Log.d(TAG, "onNodeDiscovered " + node.getTag());
        }//onNodeDiscovered
    };

    /**
     * method start a discovery and update the gui for the new state
     */
    private void startNodeDiscovery() {
        //add the listener that will hide the progress indicator when the first device is discovered
        mManager.addListener(mUpdateDiscoverGui);
        //disconnect all the already discovered device
        NodeConnectionService.disconnectAllNodes(this);
        //add as listener for the new nodes

    }

    public void stopNodeDiscovery() {
        mManager.removeListener(mUpdateDiscoverGui);
    }

    private void resetNodeList(){
        mManager.resetDiscovery();
        mManager.removeNodes();
        //some nodes can survive if they are bounded with the device
        //mAdapter.addAll(mManager.getNodes());
    }


    /**
     * 删除一个文件
     *
     * @param filePath 要删除的文件路径名
     * @return true if this file was deleted, false otherwise
     */
    public  boolean deleteFile(String filePath) {
        try {
            File file = new File(filePath);
            if (file.exists()) {
                return file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    private void deleteAllFiles(File root) {
        File files[] = root.listFiles();
        if (files != null)
            for (File f : files) {
                if (f.isDirectory()) { // 判断是否为文件夹
                    deleteAllFiles(f);
                    try {
                        f.delete();
                    } catch (Exception e) {
                    }
                } else {
                    if (f.exists()) { // 判断是否存在
                        deleteAllFiles(f);
                        try {
                            f.delete();
                        } catch (Exception e) {
                        }
                    }
                }
            }
    }


    private void loadingDialog() {
        loadingPopup = (LoadingPopupView) new XPopup.Builder(FirmwareUpgradeActivity.this)
                .dismissOnTouchOutside(false)
                .asLoading("您请稍等，正在下载固件资源")
                .show();
    }

    private void dissDialog() {
        if(loadingPopup != null){
            loadingPopup.delayDismissWith(1000, new Runnable() {
                @Override
                public void run() {
//                ToastUtils.showShort("联系师父不成功");
                }
            });
        }
    }


    @Override
    public void onClickSure(int type) {
        finishAffinity();
    }
}
